//
//  AuditController.m
//  YiBaoStore
//
//  Created by 毛云河 on 2018/12/26.
//  Copyright © 2018 小河. All rights reserved.
//

#import "AuditController.h"

@interface AuditController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSMutableDictionary *attributesDic;
@property (nonatomic, copy) NSString *nextPageInfo;

@property (nonatomic, strong) YHAlertView *alertView;

@end

@implementation AuditController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.bgNavView.hidden = YES;
    [self createTableView];
    
    self.dataArray = [NSMutableArray array];
    [self httpRequestData];//
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSString *isReload = USER_DEFAULTS_GET(@"isReload");
    if ([isReload isEqualToString:@"2"])
    {
        USER_DEFAULTS_SAVE(@"", @"isReload");
        [self httpRequestNewData];
    }
}

#pragma mark - 请求审核商品
- (void)httpRequestData
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:@"false" forKey:@"isPlatform"];//是否平台商品
    [dic setValue:@"2" forKey:@"itemState"];//商品状态
    if (NOEmptyStr(self.nextPageInfo))
    {
        [dic setValue:self.nextPageInfo forKey:@"nextPageInfo"];//翻页
    }
    __weak AuditController *myself = self;
    [HttpRequest formPostPath:SearchGoods_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
     {
         NSLog(@"已上架商品--%@",Data);
         if (msgModel.status == 200)
         {
             myself.attributesDic = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)Data[@"attributes"]];
             
             NSDictionary *result = (NSDictionary *)Data[@"result"];
             myself.nextPageInfo = result[@"nextPageInfo"];
             NSArray *currentPageResult = result[@"currentPageResult"];
             //            NSLog(@"currentPageResult--%@",currentPageResult);
             //            NSLog(@"nextPageInfo--%@",myself.nextPageInfo);
             
             NSError *error;
             if (currentPageResult.count == 0|| [currentPageResult[0] allKeys].count == 0)
             {
                 [myself.myTableView.mj_footer endRefreshingWithNoMoreData];
             }
             else {
                 for (NSDictionary *dic in currentPageResult)
                 {
                     MainModel *model = [[MainModel alloc] initWithDictionary:dic error:&error];
                     [myself.dataArray addObject:model];
                     NSLog(@"已上架商品dic--%@",dic);
                 }
             }
             [myself.myTableView.mj_header endRefreshing];
             [myself.myTableView.mj_footer endRefreshing];
             myself.myTableView.tableHeaderView = [self tableViewHeader];
             [myself.myTableView reloadData];
         }
         else {
             [myself.myTableView.mj_header endRefreshing];
             [myself.myTableView.mj_footer endRefreshingWithNoMoreData];
         }
         
     }];
}

#pragma mark - 下拉刷新
- (void)httpRequestNewData
{
    [self.dataArray removeAllObjects];
    self.nextPageInfo = nil;
    [self httpRequestData];//
}

#pragma mark - 上拉加载更多
- (void)httpMoreData
{
    if (IsEmptyStr(self.nextPageInfo))
    {
        [self.myTableView.mj_footer endRefreshingWithNoMoreData];
    }else {
        [self httpRequestData];//
    }
}

- (void)createTableView
{
    if (@available(iOS 11.0, *))
    {
        self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT-46-40-TopBarHeight_xs-BottomHeight_xs-TopBarHeight) style:UITableViewStylePlain];
    }
    else {
        self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT-46-40-TopBarHeight-BottomHeight-TopBarHeight) style:UITableViewStylePlain];
    }
    self.myTableView.backgroundColor = RGBACOLOR(241, 241, 241, 1);
    [self.view addSubview:self.myTableView];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.sectionHeaderHeight = 0.01f;
    self.myTableView.sectionFooterHeight = 10.f;
    self.myTableView.tableFooterView = [self tableViewFoot];
    self.myTableView.tableHeaderView = [self tableViewHeader];
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(httpRequestNewData)];
    self.myTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(httpMoreData)];
    [TTKUtil setAutomaticallyAdjustsScrollViewInsetsWidth:self.myTableView withView:self];
    [self.myTableView registerClass:[StorageShoppingCell class] forCellReuseIdentifier:@"StorageShoppingCell"];
}

- (UIView *)tableViewHeader
{
    UIView *view = [[UIView alloc] init];
    NSInteger amountOne = [(NSString *)self.attributesDic[@"amountOne"] integerValue];
    NSInteger amountTwo = [(NSString *)self.attributesDic[@"amountTwo"] integerValue];
    NSInteger totalCount = [(NSString *)self.attributesDic[@"totalCount"] integerValue];
    if (totalCount > 0)
    {
        view.frame = CGRectMake(0, 0, SCREENWIDTH, 48);
    }else {
        view.frame = CGRectMake(0, 0, SCREENWIDTH, 0);
    }
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *numberLabel = [[UILabel alloc] init];
    [view addSubview:numberLabel];
    numberLabel.frame = CGRectMake(SCREENWIDTH-200-15, 19, 200, 14);
    numberLabel.textAlignment = 2;
    numberLabel.textColor = RGBACOLOR(153, 153, 153, 1);
    numberLabel.font = FontWithSize(12);
    numberLabel.text = [NSString stringWithFormat:@"共%ld件",totalCount];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    [view addSubview:titleLabel];
    titleLabel.frame = CGRectMake(15, 18, 260, 12);
    titleLabel.textColor = RGBACOLOR(153, 153, 153, 1);
    titleLabel.textAlignment = 0;
    titleLabel.font = FontWithSize(12);
    titleLabel.text = [NSString stringWithFormat:@"审核中：%ld件   审核失败：%ld件",amountOne,amountTwo];
    [titleLabel sizeToFit];
    
    return view;
}

- (UIView *)tableViewFoot
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 0.01)];
    return view;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [self.myTableView tableViewDisplayWitMsg:@"您还没有任何审核商品" ifNecessaryForRowCount:self.dataArray.count withBottonTitle:@"去上架"];
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 145.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StorageShoppingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StorageShoppingCell"];
    cell.index = 2;
    
    MainModel *model = self.dataArray[indexPath.row];
    [cell setCellWithMode:model];
    
    cell.editBtn.indexPath = indexPath;
    cell.delectBtn.indexPath = indexPath;
    cell.putawayBtn.indexPath = indexPath;
    
    [cell.editBtn addTarget:self action:@selector(editBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //删除
    [cell.delectBtn addTarget:self action:@selector(delectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //上架
    [cell.putawayBtn addTarget:self action:@selector(putawayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)editBtnClick:(UIButton *)sender
{
    NSLog(@"编辑商品");
    MainModel *model = self.dataArray[sender.indexPath.row];
    EditGoodsController *editVC = [[EditGoodsController alloc] init];
    editVC.model = model;
    editVC.index = 2;
    editVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:editVC animated:YES];
}

- (void)delectBtnClick:(UIButton *)sender
{
    NSLog(@"在这个界面是删除");
    MYHAleartView *alertView = [[MYHAleartView alloc] initMecommendAlertViewWithMessage:@"确认要删除该商品吗？" fuText:@"" sureBtnTitle:@"确认删除" cancleBtnTitle:@"保留商品"];
    [alertView showAlertView];
    
    MainModel *model = self.dataArray[sender.indexPath.row];
    NSInteger index = sender.indexPath.row;
    __weak AuditController *myself = self;
    
    alertView.sureBlock = ^(id  _Nonnull sender)
    {
        NSLog(@"确认删除");
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:model.product_id forKey:@"itemId"];
        [dic setValue:@"-1" forKey:@"state"];
        
        [HttpRequest formPostPath:UpdateShoppingState_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
         {
             if (msgModel.status == 200)
             {
                 [myself.dataArray removeObjectAtIndex:index];
                 [myself.myTableView reloadData];
             }
         }];
    };
}

- (void)putawayBtnClick:(UIButton *)sender
{
    NSLog(@"在这个界面是上架");
    MainModel *model = self.dataArray[sender.indexPath.row];
    self.alertView = [[YHAlertView alloc] initPutawayAlertViewWithModel:model];
    [self.alertView showAlertView];
    
    __weak AuditController *myself = self;
    self.alertView.BtnBlock = ^(NSInteger index)
    {
        if (index == 1)
        {//去编辑界面
            EditGoodsController *editVC = [[EditGoodsController alloc] init];
            editVC.model = model;
            editVC.index = 2;
            editVC.hidesBottomBarWhenPushed = YES;
            [myself.navigationController pushViewController:editVC animated:YES];
        }
        else {//2 确认上架
            [myself surePutaway:sender.indexPath];
        }
    };
}

- (void)surePutaway:(NSIndexPath *)indexPath
{
     MainModel *model = self.dataArray[indexPath.row];
    
    __weak AuditController *myself = self;
     NSMutableDictionary *dic = [NSMutableDictionary dictionary];
     [dic setValue:model.product_id forKey:@"itemId"];
     [dic setValue:@"2" forKey:@"state"];
     
     [HttpRequest formPostPath:UpdateShoppingState_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
     {
         if (msgModel.status == 200)
         {
             [myself.alertView removeAlerrView];
             [self ShowHUDWithMessage:@"上架成功"];
             [myself httpRequestNewData];
             [myself.myTableView reloadData];
         }
         else {
             [self ShowHUDWithMessage:@"上架失败"];
         }
     }];
}


@end
